package lab5;

import java.awt.*;       // Old library classes, you still need them
import java.awt.event.*;
import javax.swing.*;    // New library classes, Swing extends AWT

/**
 * Frame to hold a bouncing ball panel, implemented in the BallPanel class.
 * Controls the animation of the ball via pauses and calls to BallPanel's move and
 * paintComponent methods.
 * @author Michael Peterson
 */
public class BallTest extends JFrame {
    
    // size of the window
    private static final int WINDOW_WIDTH = 500;
    private static final int WINDOW_HEIGHT = 300;
    
    // panel containing the bouncing ball
    private BallPanel ballPanel;
    
    /**
     * Pause command used to control the speed of the bouncing ball animation.
     * Currently pauses for 20 ms.  Use smaller values for faster animation and
     * vice versa.
     */
    public static void pause()
    {
        try {
            Thread.sleep(20); // pause for 20 ms
        } catch(Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }
    
    /** Creates a new instance of BallTest */
    public BallTest() {
        super("Bouncing Ball");  // set frame name
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
        setLayout( new BorderLayout() );
        ballPanel = new BallPanel();
        add(ballPanel);
        center(this);
        setVisible(true);
        
        // infinite animation loop, program halts when window is closed.
        while (true) {
            pause(); 
            ballPanel.move();
            ballPanel.repaint();
        }
        
    }
    
    /** Helper routine to center a frame on the screen (will cause problems if
        frame is bigger than the screen!)
     */
    public static void center(JFrame frame) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Point center = ge.getCenterPoint();
        
        int w = frame.getWidth();
        int h = frame.getHeight();
        
        int x = center.x - w/2, y = center.y - h/2;
        frame.setBounds(x, y, w, h);
        frame.validate();
    }
    
    public static void main(String[] args)
    {
        BallTest t = new BallTest();
    }
    
}
